import React from 'react';
import cx from 'classnames'
import styles from '../styles/form/pcinput'

export default React.createClass({

    getInitialState: function () {
        return {
            errMsg: null,
        };
    },
    componentWillUpdate: function(props,s) {
        if(props.showErr && !s.errMsg){
            let value = this.refs.input.value;
            let validate = this.props.validate;
            if(!value && this.props.required){
                s.errMsg = '请填写';
            }else if(validate){
                let errMsg =  validate(value);
                s.errMsg = errMsg;
            }
        }
    },
    render: function() {
        return (
                <div className={cx("pc-input", this.props.className, cx({'has-error': this.state.errMsg}))}>
                    <input type={this.props.type || "text"}
                           ref="input"
                           placeholder={this.props.placeholder}
                           onChange={this.change}
                           onFocus={this.props.onFocus}
                           disabled={this.props.disabled}
                           step={this.props.step}
                           defaultValue={this.props.defaultValue||''}
                           maxLength={this.props.maxLength}
                           onBlur={this.blur}/>
                    {this.state.errMsg?<span className="red f12 err-msg">{this.state.errMsg}</span>:null}
                </div>
        );
    },

    change: function(){
        let value = this.refs.input.value;
        let validate = this.props.validate;
        if(!value && this.props.required){
            this.setState({errMsg:'请填写'})
        }else if(validate){
            let errMsg =  validate(value);
            this.setState({errMsg,})
            if(errMsg){
                value = '';
            }
        }
        let onChange = this.props.onChange;
        if(onChange){
            onChange(value);
        };
    },

    blur:function () {
       this.change();
        if(this.props.onBlur)this.props.onBlur();
    },
});